export const processCollections = [
  'START',
  'CONDITION_RELATION',
  'OPTION_RELATION',
  'RESULT_ADJUST',
] as const;
export type ProcessType = (typeof processCollections)[number];

const getCircularReplacer = () => {
  const seen = new WeakSet();
  return (_key, value) => {
    if (typeof value === 'object' && value !== null) {
      if (seen.has(value)) {
        return;
      }
      seen.add(value);
    }
    return value;
  };
};
export class JobStep {
  prev?: JobStep;
  next?: JobStep;
  process?: ProcessType;
  data: Record<string, any>;
  isEdit: boolean;
  constructor(process?: ProcessType, data?: Record<string, any>) {
    this.process = process;
    this.data = data ?? {};
    this.isEdit = false;
  }

  addNext(step: JobStep) {
    let prev: JobStep = this;
    while (prev.next) {
      prev = prev.next;
    }
    prev.next = step;
    step.prev = prev;
  }

  format() {
    // 格式化输出
    const res: unknown[] = [];
    let head: JobStep | undefined = this;
    while (head) {
      res.push({
        process: head.process,
        data: head.data,
      });
      head = head.next;
    }
    // return res;
    return JSON.stringify(res, getCircularReplacer());
  }

  getStep(processName: ProcessType) {
    const find = (direct: 'left' | 'right') => {
      let head: JobStep | undefined = this;
      while (head) {
        if (head.process == processName) {
          return head;
        }
        if (direct == 'left') {
          head = head.prev;
        } else {
          head = head.next;
        }
      }
    };
    const left = find('left');
    if (left) return left;
    const right = find('right');
    if (right) return right;
  }

  updateStep(processName: ProcessType, data: Record<string, any>) {
    const step = this.getStep(processName);
    if (step) {
      step.data = data;
    }
  }

  modifyStatusUpdate(isEdit: boolean) {
    this.isEdit = isEdit;
  }
}
